var stompClient = null;

function connect() {
    var socket = new SockJS('/chat');
    stompClient = Stomp.over(socket);
    stompClient.connect({}, function (frame) {
        console.log('Connected: ' + frame);
        stompClient.subscribe('/topic/messages', function (message) {
            showMessage(JSON.parse(message.body));
        });
    });
}

function disconnect() {
    if (stompClient !== null) {
        stompClient.disconnect();
    }
    console.log("Disconnected");
}

function sendMessage() {
    var name = document.getElementById('name').value;
    var message = document.getElementById('message').value;
    stompClient.send("/app/chat", {}, JSON.stringify({'name': name, 'message': message}));
}

function showMessage(message) {
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(message.name + ': ' + message.message));
    document.getElementById('messages').appendChild(div);
}

connect();
